cmake_minimum_required(VERSION 2.6)

PROJECT(uhttpd C)

INCLUDE (CheckFunctionExists)

IF(NOT TLS_SUPPORT)
	SET(TLS_SUPPORT "openssl")
ENDIF()

OPTION(CGI_SUPPORT "CGI support" ON)
OPTION(LUA_SUPPORT "Lua support" ON)
OPTION(UBUS_SUPPORT "ubus support" ON)

ADD_DEFINITIONS(-Os -Wall --std=gnu99 -Wmissing-declarations)

IF(DEBUG)
	ADD_DEFINITIONS(-DDEBUG -g3)
	IF(NO_OPTIMIZE)
		ADD_DEFINITIONS(-O0)
	ENDIF()
ENDIF()

IF(APPLE)
	INCLUDE_DIRECTORIES(/opt/local/include)
	LINK_DIRECTORIES(/opt/local/lib)

	SET(CMAKE_SHARED_MODULE_CREATE_C_FLAGS "${CMAKE_SHARED_MODULE_CREATE_C_FLAGS} -undefined dynamic_lookup")
ENDIF()

CHECK_FUNCTION_EXISTS(getspnam HAVE_SHADOW)
IF(HAVE_SHADOW)
	ADD_DEFINITIONS(-DHAVE_SHADOW)
ENDIF()

SET(SOURCES uhttpd.c uhttpd-file.c uhttpd-utils.c)
FIND_LIBRARY(LIBS crypt)
IF(LIBS STREQUAL "LIBS-NOTFOUND")
	SET(LIBS "")
ENDIF()
SET(TLS_CFLAGS)

IF(CGI_SUPPORT)
	SET(SOURCES ${SOURCES} uhttpd-cgi.c)
	ADD_DEFINITIONS(-DHAVE_CGI)
ENDIF()

IF(NOT TLS_SUPPORT STREQUAL "none")
	ADD_DEFINITIONS(-DHAVE_TLS ${TLS_CFLAGS})
	ADD_LIBRARY(uhttpd_tls MODULE uhttpd-tls.c)
	SET(PLUGINS ${PLUGINS} uhttpd_tls)
ENDIF()

IF(TLS_SUPPORT STREQUAL "none")
ELSEIF(TLS_SUPPORT STREQUAL "openssl")
	ADD_DEFINITIONS(-DTLS_IS_OPENSSL)
	TARGET_LINK_LIBRARIES(uhttpd_tls ${TLS_LDFLAGS} ssl)
ELSEIF(TLS_SUPPORT STREQUAL "cyassl")
	ADD_DEFINITIONS(-DTLS_IS_CYASSL)
	TARGET_LINK_LIBRARIES(uhttpd_tls ${TLS_LDFLAGS} cyassl)
ELSE()
	MESSAGE(FATAL_ERROR "Invalid TLS provider option, use none|openssl|cyassl")
ENDIF()

IF(UBUS_SUPPORT)
	ADD_DEFINITIONS(-DHAVE_UBUS)
	ADD_LIBRARY(uhttpd_ubus MODULE uhttpd-ubus.c)
	TARGET_LINK_LIBRARIES(uhttpd_ubus ubox ubus json blobmsg_json)
	SET(PLUGINS ${PLUGINS} uhttpd_ubus)
ENDIF()

IF(LUA_SUPPORT)
	FIND_PROGRAM(PKG_CONFIG pkg-config)

	IF(NOT LUA_CFLAGS AND PKG_CONFIG)
		EXECUTE_PROCESS(
			COMMAND pkg-config --silence-errors --cflags lua5.1
			OUTPUT_VARIABLE LUA_CFLAGS
			OUTPUT_STRIP_TRAILING_WHITESPACE
		)
	ENDIF()

	IF(NOT LUA_LIBS AND PKG_CONFIG)
		EXECUTE_PROCESS(
			COMMAND pkg-config --silence-errors --libs lua5.1
			OUTPUT_VARIABLE LUA_LIBS
			OUTPUT_STRIP_TRAILING_WHITESPACE
		)
	ENDIF()

	IF(NOT LUA_LIBS)
		SET(LUA_LIBS "lua")
	ENDIF()

	ADD_DEFINITIONS(-DHAVE_LUA ${LUA_CFLAGS})
	ADD_LIBRARY(uhttpd_lua MODULE uhttpd-lua.c)
	TARGET_LINK_LIBRARIES(uhttpd_lua ${LUA_LIBS} m dl)
	SET(PLUGINS ${PLUGINS} uhttpd_lua)
ENDIF()

ADD_EXECUTABLE(uhttpd ${SOURCES})

TARGET_LINK_LIBRARIES(uhttpd ubox dl ${LIBS})

IF(PLUGINS)
	SET_TARGET_PROPERTIES(${PLUGINS} PROPERTIES
		PREFIX ""
	)
ENDIF()

INSTALL(TARGETS uhttpd ${PLUGINS}
	RUNTIME DESTINATION bin
	LIBRARY DESTINATION lib
)
